import {login, logout, phoneLogin} from '../../network/user'
import router from '../../router/index'
import { Message } from 'element-ui'


const getDefaultState = () => {
  return {
    token: localStorage.getItem("common_TOKEN"),
    userName:localStorage.getItem("common_userName"),
  }
}

const state = getDefaultState()

const mutations = {
  SET_USERNAME:(state,userName)=>{
    state.userName=userName
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  }
}


const actions = {
  // user login
  login({ commit }, userInfo) {
    const {username, password,code} = userInfo
    return new Promise((resolve, reject) => {
      login({ userName: username.trim(), password: password,captcha:code}).then(response => {
        const { data } = response
        if(data.code==100){
          commit('SET_TOKEN', data.data[1])
          commit('SET_USERNAME',username)
          localStorage.setItem("common_TOKEN",data.data[1])
          localStorage.setItem("common_userName",username);
          localStorage.setItem("common_userId",data.data[0].userId);
          Message.success("登录成功!欢迎回来~")
          router.push({ path: this.redirect || '/personalCenter' })
        }else{
          Message.warning(data.extend.msg)
        }
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  phoneLogin({ commit }, userInfo) {
    const {tel,code} = userInfo
    return new Promise((resolve, reject) => {
      phoneLogin({ tel: tel, captcha:code}).then(response => {
        const { data } = response
        if(data.code==100){
          console.log(data.data[0])
          console.log(data.data[1])
          commit('SET_TOKEN', data.data[1])
          commit('SET_USERNAME',data.data[0].userName)
          localStorage.setItem("common_TOKEN",data.data[1])
          localStorage.setItem("common_userName",data.data[0].userName);
          localStorage.setItem("common_userId",data.data[0].userId);
          Message.success("登录成功!欢迎回来~")
          router.push({ path: this.redirect || '/personalCenter' })
        }else{
          Message.warning(data.extend.msg)
        }
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },


  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        // must remove  token  first
        localStorage.removeItem("common_TOKEN")
        localStorage.removeItem("common_userName")
        localStorage.removeItem("common_userId");
        commit('SET_TOKEN','');
        Message.success("账号已退出~")
        router.push("/login")
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
}


export default {
  namespaced: true,
  state,
  mutations,
  actions
}

